package com.book.controller.admin;

import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.book.common.BaseController;
import com.book.entity.Teacher;
import com.book.utils.BeanUtils;
import com.book.utils.FTPTool;
import com.github.drinkjava2.jsqlbox.ActiveRecord;
import com.google.common.base.Strings;




/**
*
*      用户控制类
*
*/
@Controller
@RequestMapping("/s/{admin}}/user")
public class UserController { 
	
	@Autowired
	private FTPTool ftpTool;

	public UserController() {
		super(); 
	}
	
	@GetMapping({"","/"})
	public String index(Model m) throws Exception {
		System.out.println("进入 UserController 的 index 方法。。。。");
		
		
		m.addAttribute("datalist", new Teacher().findAll());

		return "admin/user/list";

	}
	
	@GetMapping("")
	public String add(Model m ) throws Exception {
		
			m.addAttribute("eo",new Teacher());
		return "/admin/user/edit";
	
	}

	@GetMapping("/del/{id}")
	@ResponseBody
	public String del(@PathVariable Integer id) throws Exception {

		try {
			new Teacher().deleteById(id);
		} catch (Exception e) { 
			e.printStackTrace();
			return "删除失败，请检查";
		}
		return "删除成功";
	}
	
	
	
	
	
	@GetMapping("/edit/{id}")
	public  String edit(@PathVariable Integer id, Model m) throws Exception {
           
		Teacher eo = new Teacher().loadById(id);

			m.addAttribute("eo",eo);
		
		return "admin/user/edit";
		
	}
	
	
	
	
	public Teacher getRecord() {
		return new Teacher();
	}
	
	@GetMapping("/query")
	public String query(@RequestParam(required=false) String nicheng,@RequestParam(required=false) String username,Model m) throws Exception {
		System.out.println("进入 UserController 的 query 方法。。。。");
		
		if(!Strings.isNullOrEmpty(username)) {
			m.addAttribute("datalist", getRecord().findAll(String.format(" where username like '%s'", "%"+ username +"%")));
		}else if(nicheng != null && !"".equals(nicheng .trim())) {
			m.addAttribute("datalist", getRecord().findAll(String.format(" where nicheng like '%s'", "%"+ nicheng +"%")));
		}else {
			m.addAttribute("datalist", getRecord().findAll());
		}
		return "admin/user/list";

	}
	
	
	@PostMapping("/save")
	@ResponseBody
		public String save( Teacher eo,MultipartFile imgUrlFile,HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
		
				
			 
			
		
		
		Object pkvalue =  eo.getId();
		
		
		try {
		  //判断当前是新增 还是修改   
		if(pkvalue != null && ((Integer)pkvalue)>0) {
			
			if(imgUrlFile!=null) {
				// 创建文件上传核心类
						String imgUrl = eo.getImgUrl();
						
						if(Strings.isNullOrEmpty(imgUrl)) {
							imgUrl = "/" + System.nanoTime() + ".jpg";	
						}
						

						try {
							ftpTool.connect();
							ftpTool.uploadFileFromIS(imgUrl, imgUrlFile.getInputStream());
							eo.setImgUrl(imgUrl);
							System.out.println(String.format("Name = %s; Value = %s", "imgUrl",imgUrl));
						} catch (Exception e) {
							e.printStackTrace();
						}
				}
			
				//修改
				eo.update();
		}else {
			if(imgUrlFile!=null) {
			// 创建文件上传核心类
					String imgUrl = "/" + System.nanoTime() + ".jpg";
					try {
						ftpTool.connect();
						ftpTool.uploadFileFromIS(imgUrl, imgUrlFile.getInputStream());
						eo.setImgUrl(imgUrl);
						System.out.println(String.format("Name = %s; Value = %s", "imgUrl",imgUrl));
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
			//新增
			eo.insert();
		   }		 
		}catch (Exception e) {
			e.printStackTrace();
			if(e.getMessage().contains("Duplicate entry")) {
				//有条目重复
				String msg = e.getMessage();
				int beginIndex = msg.indexOf("for key")+7;
				int endIndex = msg.indexOf("Query:");
				String key = msg.substring(beginIndex,endIndex);
				return String.format("%s重复，请重新填写", key);
			}else {
				return "更新失败，请联系管理员检查日志";
			}
			
			
		}	
				return "更新成功！";
	}
}
	

